// Packing Information Client Script
frappe.ui.form.on("Packing Information", {
    refresh: function (frm) {
        // 如果已有物料申请单，显示物料列表
        if (frm.doc.material_request && frm.material_request_items_data) {
            show_material_request_items(frm);
            add_excel_import_button(frm);
        }
        add_excel_import_button(frm);
    },
    
    material_request: function(frm) {
        if (frm.doc.material_request) {
            // 清空现有明细
            frm.clear_table('packing_item');
            frm.refresh_field('packing_item');
            
            // 设置默认值
            frm.set_value('total_boxes', 1);
            
            // 获取物料申请单的物料列表并存储到界面
            frappe.call({
                method: 'frappe.client.get',
                args: {
                    doctype: 'Material Request',
                    name: frm.doc.material_request
                },
                callback: function(r) {
                    if (r.message && r.message.items) {
                        // 将物料列表存储到frm对象中，供查询过滤器使用
                        frm.material_request_items = r.message.items.map(item => item.item_code).filter(Boolean);
                        frm.material_request_items_data = r.message.items.map(item => ({
                            item_code: item.item_code,
                            item_name: item.item_name,
                            qty: item.qty,
                            uom: item.uom || item.stock_uom
                        })).filter(item => item.item_code);
                        
                        // 显示物料列表表格
                        show_material_request_items(frm);
                        add_excel_import_button(frm);
                        
                        // 刷新字段
                        frm.refresh_field('packing_item');
                    }
                }
            });
        } else {
            // 清空物料列表
            frm.material_request_items = [];
            frm.material_request_items_data = [];
            // 隐藏物料列表表格
            hide_material_request_items(frm);
        }
    },
    
    total_boxes: function(frm) {
        // 当总箱数改变时，验证现有箱子编号
        if (frm.doc.packing_item) {
            console.log('total_boxes changed, refreshing packing_item');
            frm.refresh_field('packing_item');
        }
    },
    
    before_save: function(frm) {
        return validate_packing_info(frm);
    }
});

frappe.ui.form.on('Packing Item', {
    item: function(frm, cdt, cdn) {
        let row = locals[cdt][cdn];
        if (row.item) {
            // 验证物料代码是否在申请单中
            if (frm.material_request_items && frm.material_request_items.length > 0 && !frm.material_request_items.includes(row.item)) {
                frappe.msgprint({
                    title: __("Validation Failed"),
                    message: __("Item {0} is not in Material Request", [row.item]),
                    indicator: "red"
                });
                frappe.model.set_value(cdt, cdn, 'item', '');
                return;
            }
        }
    },
    
    item_name: function(frm, cdt, cdn) {
        let row = locals[cdt][cdn];
        if (row.item_name) {
            // 验证物料名称是否在申请单中
            if (frm.material_request_items_data && frm.material_request_items_data.length > 0) {
                let valid_names = frm.material_request_items_data.map(item => item.item_name);
                if (!valid_names.includes(row.item_name)) {
                    frappe.msgprint({
                        title: __("Validation Failed"),
                        message: __("Item Name {0} is not in Material Request", [row.item_name]),
                        indicator: "red"
                    });
                    frappe.model.set_value(cdt, cdn, 'item_name', '');
                    return;
                }
            }
        }
    },
    
    box_no: function(frm, cdt, cdn) {
        let row = locals[cdt][cdn];
        console.log('box_no onchange triggered:', row.box_no, 'total_boxes:', frm.doc.total_boxes);
        if (row.box_no) {
            // 获取最新的总箱数
            let total_boxes = frm.doc.total_boxes || 1;
            
            // 验证箱子编号必须为正整数
            if (row.box_no < 1 || !Number.isInteger(row.box_no)) {
                frappe.msgprint({
                    title: __("Validation Failed"),
                    message: __("Box number must be a positive integer"),
                    indicator: "red"
                });
                // 不强制修改，让用户自己修正
                return;
            }
            
            // 验证箱子编号不能超过总箱数
            if (row.box_no > total_boxes) {
                frappe.msgprint({
                    title: __("Validation Failed"),
                    message: __("Box number {0} cannot exceed total boxes {1}", [row.box_no, total_boxes]),
                    indicator: "red"
                });
                // 不强制修改，让用户自己修正
                return;
            }
        }
    },
    
    qty: function(frm, cdt, cdn) {
        let row = locals[cdt][cdn];
        if (row.qty && row.qty < 0) {
            frappe.msgprint({
                title: __("Validation Failed"),
                message: __("Quantity cannot be negative"),
                indicator: "red"
            });
            frappe.model.set_value(cdt, cdn, 'qty', 0);
        }
    }
});


// 验证装箱信息
function validate_packing_info(frm) {
    return true;
}

// 添加“从Excel导入明细”按钮
function add_excel_import_button(frm) {
    frm.add_custom_button(__('从Excel导入明细'), function () {
        open_import_dialog(frm);
    });
}

function open_import_dialog(frm) {
    const d = new frappe.ui.Dialog({
        title: __('从Excel导入明细 (.xlsx)'),
        fields: [
            { fieldtype: 'Section Break' },
            { fieldtype: 'Attach', label: __('Excel 文件'), fieldname: 'file', reqd: 1, options: 'Attach' },
            { fieldtype: 'Column Break' },
            { fieldtype: 'HTML', fieldname: 'help', options: __('接受包含列：CTN No/箱号、SKU、Product Name、QTY(数量)。') }
        ],
        primary_action_label: __('导入'),
        primary_action(values) {
            if (!values || !values.file) return;
            d.set_primary_action(__('导入中...'));
            d.disable_primary_action();
            frappe.call({
                method: 'upsystem.upsystem.api_packing.parse_packing_excel',
                args: { file_url: values.file },
                callback: function (r) {
                    d.hide();
                    const data = (r && r.message) || {};
                    const rows = data.items || [];
                    if (!rows.length) {
                        frappe.msgprint(__('未解析到任何行，请检查模板与数据。'));
                        return;
                    }
                    let imported = 0;
                    let maxBox = 0;
                    rows.forEach(it => {
                        const row = frm.add_child('packing_item');
                        row.item = it.item || '';
                        row.item_name = it.item_name || '';
                        row.item_name_cn = it.item_name_cn || '';
                        row.item_color = it.item_color || '';
                        row.item_size = it.item_size || '';
                        row.batch_no = it.batch_no || '';
                        row.manufacture_date = it.manufacture_date || null;
                        row.expire_date = it.expire_date || null;
                        row.qty = it.qty || 0;
                        if (it.box_no) {
                            row.box_no = it.box_no;
                            if (it.box_no > maxBox) maxBox = it.box_no;
                        }
                        imported += 1;
                    });
                    if (maxBox && (!frm.doc.total_boxes || frm.doc.total_boxes < maxBox)) {
                        frm.set_value('total_boxes', maxBox);
                    }
                    frm.refresh_field('packing_item');
                    frappe.show_alert({ message: __('已从Excel导入 {0} 条', [imported]), indicator: 'green' });
                },
                always: function () {
                    d.enable_primary_action();
                    d.set_primary_action(__('导入'));
                }
            });
        }
    });
    d.show();
}

// 显示物料申请单的物料列表表格
function show_material_request_items(frm) {
    if (!frm.material_request_items_data || frm.material_request_items_data.length === 0) {
        return;
    }
    
    // 创建表格HTML
    let table_html = `
        <div class="material-request-items-section" style="margin: 15px 0; padding: 15px; border: 1px solid #d1d8e0; border-radius: 4px; background-color: #f8f9fa;">
            <h6 style="margin: 0 0 10px 0; color: #6c757d;">Available Items from Material Request</h6>
            <div class="table-responsive">
                <table class="table table-bordered table-sm" style="margin: 0; font-size: 12px;">
                    <thead class="thead-light">
                        <tr>
                            <th style="width: 30%;">Item Code</th>
                            <th style="width: 50%;">Item Name</th>
                            <th style="width: 20%; text-align: right;">Requested Qty</th>
                        </tr>
                    </thead>
                    <tbody>
    `;
    
    frm.material_request_items_data.forEach(item => {
        table_html += `
            <tr>
                <td><strong>${item.item_code}</strong></td>
                <td>${item.item_name || ''}</td>
                <td style="text-align: right;">${item.qty} ${item.uom || ''}</td>
            </tr>
        `;
    });
    
    table_html += `
                    </tbody>
                </table>
            </div>
        </div>
    `;
    
    // 查找物料申请单字段的位置
    let material_request_field = frm.fields_dict.material_request.$wrapper;
    if (material_request_field && material_request_field.length > 0) {
        // 移除已存在的表格
        hide_material_request_items(frm);
        
        // 在物料申请单字段下方插入表格
        material_request_field.after(table_html);
    }
}

// 隐藏物料申请单的物料列表表格
function hide_material_request_items(frm) {
    $('.material-request-items-section').remove();
}


